const { Op, where } = require("sequelize");
const sequelize = appRequire('db');
var COS = require('cos-nodejs-sdk-v5');
const posterModel = appRequire('models/poster');
const path = require('path');
const fs = require('fs');
const axios = require('axios');

// 导出对象，供其它模块调用
module.exports = {
    asyncPosterType,
    asyncPosterType2,
    asyncPosterData3,
    asyncPosterFont,
    findPoster
};


async function findPoster(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let results = await posterModel.poster.findAll({
        where: {
            [Op.or]: [
                { id: { [Op.substring]: postData.searchText } },
                { thumbnail: { [Op.substring]: postData.searchText } }
            ],
        }
    })

    returnData.data = Common.clone(results)
    return request.json(returnData)
}

async function asyncPosterFont(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    for (let item of postData.data) {
        posterModel.fonts.create({
            id: item.id,
            fileName: item.fileName,
            fileUrl: "https://qiniu.jimuzhou.cloud/fontFiles/" + item.fileName,
            fontName: item.fontName,
            fontValue: item.fontValue,
        })
    }

    return request.json(returnData)
}

async function asyncPosterType(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    for (let item of postData.dataList) {
        posterModel.postType.create({
            id: item.id,
            bclazzs: item.bclazzs,
            name: item.name,
            topicImage: item.topicImage,
            topicPath: item.topicPath,
        })
    }

    return request.json(returnData)
}

async function asyncPosterType2(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    posterModel.postTag.create(postData.dataList)

    return request.json(returnData)
}

async function asyncPosterData3(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    if (postData.isDelete) {
        let result = await posterModel.poster.destroy({
            where: {
                id: postData.data.id
            }
        });
    }

    const updateData = async (item, data2) => {
        // 模拟异步操作，例如网络请求
        return new Promise(async (resolve, reject) => {
            if (item.picType == "2" || item.path.includes("54e7c1e5-781a-4ac5-bedc-049318cb6cd9")) {
                item.path = "https://qiniu.jimuzhou.cloud/common/basicprofile.png"
                resolve(item)
            } else if (item.picType == "1"
                || item.path.includes("3545c511-1b7a-4041-9266-edf7d6d5c00b")
                || item.path.includes("115dcc3-03e3-41f4-8778-d4c170bf918e")) {
                item.path = "https://qiniu.jimuzhou.cloud/common/qrcode.png"
                resolve(item)
            } else {
                let thisId1 = item.id
                let imagePath1 = path.join(__dirname, `image/${data2.id}/${thisId1}.png`);
                await downloadImage(item.path, imagePath1)
                item.path = await uploadImageQiniu(imagePath1, { mainId: data2.id, id: thisId1 })
                resolve(item)
            }
        });
    };

    const updateDataBatch = async (dataList, data2) => {
        const updatedItems = [];
        for (const item of dataList) {
            try {
                console.log(item)
                const updatedItem = await updateData(item, data2);
                updatedItems.push(updatedItem);
            } catch (error) {
                // 错误处理
                console.error(error);
            }
        }
        return updatedItems;
    };

    let data = postData.data
    delete data.elements
    let result1 = await posterModel.poster.findOne({
        where: {
            id: data.id
        }
    })
    result1 = Common.clone(result1)
    if (result1) {
        posterModel.poster.update(data, {
            where: {
                id: data.id
            }
        })
    } else {
        posterModel.poster.create(data)
    }

    let url = "http://localhost:8082/?id=" + data.id;

    fs.mkdir(path.join(__dirname, `image/${data.id}`), function (err) {
        //console.log(err)
    })
    const imagePath = path.join(__dirname, `image/${data.id}/${data.id}.png`);


    
}

async function downloadImage(url, imagePath) {
    const writer = fs.createWriteStream(imagePath);
    const response = await axios({
        url: url,
        method: 'GET',
        responseType: 'stream'
    });
    response.data.pipe(writer);
    return new Promise((resolve, reject) => {
        writer.on('finish', () => resolve(imagePath));
        writer.on('error', reject);
    });
}

async function uploadImageQiniu(filePath, item) {
    var qiniu_sdk = require("qiniu");
    return new Promise((resolve, reject) => {
        qiniu_sdk.conf.ACCESS_KEY = '3hOARVprmGFiKcb1MgcwJxSgZkUOe_zUyjPXUlet';
        qiniu_sdk.conf.SECRET_KEY = 'wzxXaNfuhhDdJiYaEIwEQvKYe3_7QmJnvXzTpKkg';
        // 要上传的空间
        const bucket = 'artppt109063';
        // 文件前缀
        const prefix = 'posterFiles/' + item.mainId + "/"
        // 生成上传文件的 token
        const token = (bucket, key) => {
            const policy = new qiniu_sdk.rs.PutPolicy({ scope: bucket + ':' + key })
            return policy.uploadToken()
        }

        const config = new qiniu_sdk.conf.Config()
        const upload_file = (file_name, file_path) => {
            // 保存到七牛的地址
            const file_save_path = prefix + file_name
            // 七牛上传的token
            const up_token = token(bucket, file_save_path)
            const extra = new qiniu_sdk.form_up.PutExtra()
            const formUploader = new qiniu_sdk.form_up.FormUploader(config)
            // 上传文件
            formUploader.putFile(up_token, file_save_path, file_path, extra, (err, ret) => {
                if (!err) {
                    // 上传成功， 处理返回值
                    console.log(ret);
                    if (ret.error == 'file exists') {
                        resolve("https://qiniu.jimuzhou.cloud/" + prefix + file_name)
                    } else {
                        resolve("https://qiniu.jimuzhou.cloud/" + ret.key)
                    }
                } else {
                    if (err.error == 'file exists') {
                        resolve("https://qiniu.jimuzhou.cloud/" + prefix + file_name)
                    }
                    // 上传失败， 处理返回代码
                    console.error(err);
                }
            });
        }

        upload_file(item.id + '.png', filePath);
    })
}

async function screenshotDOMElement(page, selector, path, padding = 0) {
    const rect = await page.evaluate(selector => {
        try {
            const element = document.querySelector(selector);
            const { x, y, width, height } = element.getBoundingClientRect();
            if (width * height != 0) {
                return { left: x, top: y, width, height, id: element.id };
            } else {
                return null;
            }
        } catch (e) {
            return null;
        }
    }, selector);

    return await page.screenshot({
        path: path,
        clip: rect ? {
            x: rect.left - padding,
            y: rect.top - padding,
            width: rect.width + padding * 2,
            height: rect.height + padding * 2
        } : null
    });
}